﻿using SterlingLib;
using System;

namespace Algobox.Interop.SterlingTrader
{
    public static class SterlingWrapper
    {
        static SterlingWrapper()
        {
            STIApp = new SterlingLib.STIApp();
            STIApp.SetModeXML(true);
            _isStarted = false;
        }

        private static bool _isStarted;

        public static bool IsEnabled { get { return STIApp.IsApiEnabled(); } }
        public static QuoteManagement QuoteManager { get; set; }
        public static OrderManagement OrderManager { get; set; }

        internal static STIApp STIApp;
        internal static STIEvents STIEvents;
        internal static STIOrderMaint STIOrderMaint;
        internal static STIOrder STIOrder;

        internal static STIQuote STIQuotes;
        internal static STIBook STIBook;

        public delegate void STIShutdown();
        public static event STIShutdown OnSterlingShutdown;

        //static System.Collections.Generic.List<string> _exchanges;

        //private static void LoadExchanges()
        //{
        //    System.Array exchanges = System.Array.CreateInstance(typeof(string), 0);
        //    int count = STIApp.GetDestinationList(ref exchanges);
        //    _exchanges = new System.Collections.Generic.List<string>((string[])exchanges);
        //}

        /// <summary>
        /// Starts the Sterling Lib API interface
        /// </summary>
        /// <returns>True when the engine starts successfully</returns>
        public static bool Start()
        {
            if (!_isStarted)
            {
                if (!STIApp.IsApiEnabled())
                    return false;

                try
                {
                    if (STIEvents == null)
                    {
                        STIEvents = new SterlingLib.STIEvents();
                    }

                    STIEvents.OnSTIShutdown += new _ISTIEventsEvents_OnSTIShutdownEventHandler(OnSTIShutdown);
                }
                catch
                {
                    return false;
                }
                _isStarted = true;
            }
            return true;
        }

        public static void Stop()
        {
            if (_isStarted)
            {
                if (STIEvents != null)
                {
                    STIEvents.OnSTIShutdown -= new _ISTIEventsEvents_OnSTIShutdownEventHandler(OnSTIShutdown);
                    STIEvents.Destroy();
                }

                _isStarted = false;
            }
        }


        public static void OnSTIShutdown()
        {
            if (OnSterlingShutdown != null)
                OnSterlingShutdown();

            _isStarted = false;
        }

    }
}
